﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="New.xaml.cs" company="Simon Carpentier">
//   Microsoft Reciprocal License (Ms-RL)
// </copyright>
// <summary>
//   Defines the New type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace VinoCellar
{
    using System;
    using System.Windows;

    using Microsoft.Phone.Controls;

    using VinoCellar.Model;

    public partial class New : PhoneApplicationPage
    {
        private WineItemFactory wineItemFactory = new WineItemFactory();
        private WineItem wineItem;

        public New()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            try
            {
                string upc;
                wineItemFactory.Loaded += new WineItemFactory.FetcherLoadedDelegate(wineItemFactory_Loaded);

                if (NavigationContext.QueryString.TryGetValue("upc", out upc))
                {
                    progressBar1.Visibility = Visibility.Visible;
                    wineDetailsControl.Visibility = Visibility.Collapsed;

                    if (!Microsoft.Phone.Net.NetworkInformation.DeviceNetworkInformation.IsNetworkAvailable)
                    {
                        MessageBox.Show(
                            "Network is required for this operation. Please, connect your phone and try again.");
                        NavigationService.GoBack();
                        return;
                    }
                    else
                    {
                        wineItemFactory.GetWineItem(upc);                        
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Something went wrong: " + ex.Message);
                NavigationService.GoBack();
            }
        }

        void wineItemFactory_Loaded(WineItem wineItem, bool alreadyExisting)
        {
            this.wineItem = wineItem;
            if (wineItemFactory.Error != string.Empty)
            {
                MessageBox.Show(
                    "Something went wrong. Are you sure this is a valid UPC code? Details: " + wineItemFactory.Error);
                NavigationService.GoBack();
                return;
            }


            // Ça se pourrait que l'item existe déjà
            if (wineItemFactory.IsExisting)
            {
                MessageBox.Show("This wine is already present in the database");
                this.NavigationService.Navigate(new Uri(string.Format("/Wine.xaml?id={0}", wineItem.WineItemId), UriKind.RelativeOrAbsolute));
            }

            wineDetailsControl.Load(wineItem);

            progressBar1.Visibility = Visibility.Collapsed;
            wineDetailsControl.Visibility = Visibility.Visible;
        }

        private void appBarOkButton_Click(object sender, EventArgs e)
        {
            // Est-ce que le data a au moins fini de loader?
            if (wineItemFactory.IsLoaded)
            {
                // Add the item to the ViewModel.
                App.ViewModel.AddWineItem(this.wineItem);

                App.ViewModel.SaveChangesToDB();

                // Refresh la page pour reloader l'item
                this.NavigationService.Navigate(new Uri(string.Format("/Wine.xaml?id={0}", this.wineItem.WineItemId), UriKind.RelativeOrAbsolute));
            }
            else
            {
                MessageBox.Show("Please wait for the data to be fetched before adding the bottle to the database");
            }
        }

        private void appBarCancelButton_Click(object sender, EventArgs e)
        {
            if (NavigationService.CanGoBack)
                NavigationService.GoBack();
            else
            {
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
            }
        }
    }
}